package com.AAL.DAO;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.classic.Session;

import com.AAL.DAO.Interface.ITypeOfAutoDAO;
import com.AAL.Model.TypeOfAuto;
import com.AAL.Utils.HibernateUtil;

public class TypeOfAutoDAO implements ITypeOfAutoDAO {

	@Override
	public TypeOfAuto saveAndUpdateTypeOfAutos(TypeOfAuto type) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		try {
			session.saveOrUpdate(type);
		} catch (Exception e) {
			return null;
		}
		session.getTransaction().commit();
		return type;
	}

	@Override
	public TypeOfAuto deleteTypeOfAuto(String typeID) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		try {
			session.beginTransaction();
			TypeOfAuto typeOfAuto = (TypeOfAuto) session.load(TypeOfAuto.class,
					typeID);
			if (null != typeOfAuto) {
				session.delete(typeOfAuto);
			}
			session.getTransaction().commit();
			return typeOfAuto;
		} catch (Exception e) {
			e.printStackTrace();
			session.getTransaction().rollback();
			return null;
		}
	}

	@Override
	public TypeOfAuto getTypeOfAuto(String typeID) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		TypeOfAuto typeOfAuto = (TypeOfAuto) session.load(TypeOfAuto.class,
				typeID);
		return typeOfAuto;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<TypeOfAuto> getAllTypeOfAutos() {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List<TypeOfAuto> lstTypeOfAutos = null;
		try {
			lstTypeOfAutos = (List<TypeOfAuto>) session.createQuery(
					"from TypeOfAuto").list();
		} catch (HibernateException e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		}
		session.getTransaction().commit();
		return lstTypeOfAutos;
	}

}
